#include "example.h"
#include "mpu6050.h"
#include "inv_mpu.h"
#include "Lora.h"
#include "stdlib.h"
#include "Light.h"
//********************************************************
// 宏定义   
//********************************************************
#define  LIGHTINFO_FLASH_ADDRESS    0x800C8000   //800K(AG32VF407RGT6型号1024K Flash，最后100K给FPGA使用)
#define  HEART_INTERVAL_6S          (600)        //心跳定时6S
#define  HEART_INTERVAL_60S         (6000)       //心跳定时60S
#define  HEART_INTERVAL_30S         (3000)       //心跳定时30S
//********************************************************
// 变量定义   
//********************************************************
uint8_t             rxbuffer[255];
uint8_t             rxBufferSize;
extern uint16_t     RxIrqMask;
extern uint16_t     TxIrqMask;
uint8_t             TxBuffer[BUFFER_SIZE];
bool                rxdone = false;
bool                txdone = false;
bool                rxtimeout=false;

uint8_t             serial_num=255;
uint8_t             sync_flag=0;                        //同步标识
int32_t             sync_interval;                      //同步计数
uint32_t            gloabal_time=0;                     //全局时钟（x10ms)
uint8_t             packet_id=0;                        //接收包id
uint8_t             updata_flash=0;                     //参数更新标识
uint32_t            tag_code[4][16];
uint8_t             uart_rx_buffer[255];
uint8_t             uart_tx_buffer[255];
uint8_t             uart_rx_length=0;
uint8_t             uart_cmd_buffer[255];               //串口接收指令
uint8_t             cmd_flag=0;                         //串口接收指令标识
uint8_t             light_serNum=0;                     //灯序号
uint32_t            heart_time=0;                       //心跳周期
//********************************************************
// 函数定义
//********************************************************
void Uart_init(void);
void Uart_Parse(void);
void radio_rx_handler();
uint16_t gen_crc(const uint8_t *buffer, int buffer_length);

//--------------------------------------------------------
// CRC8()
// CRC校验
//--------------------------------------------------------
uint8_t CRC8(uint8_t *dat,uint8_t len)
{
   uint8_t  crc_value=0xFF,j; 
   uint8_t  i;
   for(i=0;i<len;i++)
   {
       crc_value ^= *dat++;
       for(j=0;j<8;j++)
       {
            if(crc_value&0x80)
            {
                 crc_value=(crc_value<<1)^0x31;//其余的CRC校验算法修改该多项式的值即可
            }
            else
            {
                 crc_value=(crc_value<<1);
            }
       }
   }
   return crc_value;
}

//********************************************************
// Uart 中断
//********************************************************
void UART0_isr()
{
  if(UART_IsRawIntActive(UART0,UART_INT_RX))
  {
    UART_ClearInt(UART0,UART_INT_RX);
    UART_Receive(UART0,uart_rx_buffer+uart_rx_length,1,0);
    uart_rx_length++;

    if((uart_rx_buffer[0]!=0x55)|| 
       ((uart_rx_length>=2)&&(uart_rx_buffer[1]!=0xAA)))   //帧头错误                                               
    {
      uart_rx_length = 0;
      uart_rx_buffer[0]=0;
      uart_rx_buffer[1]=0;
      uart_rx_buffer[2]=0;
      uart_rx_buffer[3]=0;
    } 

    if(uart_rx_length>=(uart_rx_buffer[3]+7)) 
    {
      if(uart_rx_buffer[uart_rx_buffer[3]+6]==0xDD )
      {
        cmd_flag = 1;
        memcpy(uart_cmd_buffer,uart_rx_buffer,uart_rx_buffer[3]+7);
      }
      memset(uart_rx_buffer,0,255);
      uart_rx_length = 0; 
    }

    if(uart_rx_length>=254)                                 //指令过长
    {
      memset(uart_rx_buffer,0,uart_rx_buffer[2]+6);
      uart_rx_length = 0; 
    }
  }
}
//********************************************************
// Uart 初始化
//********************************************************
void Uart_init(void)
{
  PERIPHERAL_ENABLE(UART,0);
  SYS_EnableAPBClock(APB_MASK_UART0);
  UART_Init(UART0,
            UART_BAUDRATE_115200, 
            UART_LCR_DATABITS_8,
            UART_LCR_STOPBITS_1, 
            UART_LCR_PARITY_NONE, 
            UART_LCR_FIFO_1
            );
  UART_EnableInt(UART0,UART_INT_RX);
  INT_EnableIRQ(UART0_IRQn,UART_PRIORITY);
}
//********************************************************
// 射频发送及接收
//********************************************************
void send_with_timeout(uint8_t* buffer,uint8_t size,uint16_t timeout_ms)
{
   GPIO_SetHigh(RADIO_PA_GPIO_Port,RADIO_PA_Pin);     //发送
   GPIO_SetLow(RADIO_LNA_GPIO_Port, RADIO_LNA_Pin);   //接收
   Radio.SetDioIrqParams( TxIrqMask, TxIrqMask, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
   Radio.SendPayload(buffer, size, (TickTime_t){RX_TIMEOUT_TICK_SIZE,timeout_ms});                    
   while(txdone==false)
   {
   }
   txdone=false;
}

//********************************************************
// Uart 解析
//********************************************************
void print_pack_id(void)
{
   uint8_t tmp[16];
   uint16_t crc;

   tmp[0] = 0x55;
   tmp[1] = 0xAA;
   tmp[2] = 0x00;
   tmp[3] = 0x05;
   tmp[4] = 0xEE;
   memcpy(tmp+5,uart_cmd_buffer+5,4);
   crc=gen_crc(tmp+4,5);
   tmp[9] = crc>>8;
   tmp[10] = crc&0xFF;
   tmp[11] = 0xDD;
   UART_Send(UART0,tmp,12);
} 

void Uart_Parse(void)
{
  uint32_t id;
  uint8_t  freq;
  
  switch(uart_cmd_buffer[4])
  {
    case 0x77:                                              //灯复位
      printf("reset cmd!\r\n");
      TxBuffer[0] = 0xAB;                                   //帧头
      TxBuffer[1] = packet_id++;                            //帧序号
      memcpy(TxBuffer+2,uart_cmd_buffer+5,3);               //目的地址
      memset(TxBuffer+5,0xFF,3);                            //源地址
      TxBuffer[8] = 0x01;                                   //数据长度
      TxBuffer[9]= 0x77;                                    //指令号
      id = (uart_cmd_buffer[5]<<16)|(uart_cmd_buffer[6]<<8)|(uart_cmd_buffer[7]);
      freq = id/1000000;
      load_light_param(10,freq);
      TxBuffer[0] = CRC8(TxBuffer+1,9);
      send_with_timeout(TxBuffer,10,100);                   //发送
      break;

    case 0x7F:                                              //启动升级
      TxBuffer[0] = 0xAB;                                   //帧头
      TxBuffer[1] = 0x0E;                                   //帧长度
      memcpy(TxBuffer+2,uart_cmd_buffer+4,14);              //数据 
      load_boot_param(16);                  
      send_with_timeout(TxBuffer,16,100);      
      break;

    case 0x31:                                              //固件下发
      //print_pack_id();
      TxBuffer[0] = 0xAB;                                       
      memcpy(TxBuffer+1,uart_cmd_buffer+3,uart_cmd_buffer[3]+1);  
      load_boot_param(uart_cmd_buffer[3]+2);                            
      send_with_timeout(TxBuffer,uart_cmd_buffer[3]+2,500);  
      break;
    default:
      break;
  }
}
//********************************************************
// 射频回调函数
//********************************************************
void OnTxDone( void )
{
  txdone = true;
}
void OnRxDone( void )
{
  rxdone = true; 
}
void OnTxTimeout  ( void )
{
  txdone = true;
}
void OnRxTimeout  ( void )
{ 
  rxtimeout = true;
}
void OnRxError    ( IrqErrorCode_t errorCode     ){ printf("OnRxErro\r\n");     }
void OnRangingDone( IrqRangingCode_t val         ){ }//printf("OnRangingDone\r\n");}
void OnCadDone    ( bool channelActivityDetected ){ }//printf("OnCadDone\r\n");}

//********************************************************
// 射频接收接收
//********************************************************
uint8_t receive(uint16_t timeout_ms)
{
   GPIO_SetLow(RADIO_PA_GPIO_Port,RADIO_PA_Pin);       //发送
   GPIO_SetHigh(RADIO_LNA_GPIO_Port, RADIO_LNA_Pin);   //接收
   load_boot_param(BUFFER_SIZE);
   Radio.SetDioIrqParams( RxIrqMask, RxIrqMask, IRQ_RADIO_NONE, IRQ_RADIO_NONE );
   rxtimeout = false;
   rxdone = false;
   Radio.SetRx((TickTime_t){RX_TIMEOUT_TICK_SIZE,timeout_ms});  
            
   while((rxdone==false)&&(rxtimeout==false))
   {
   }
   UTIL_IdleUs(150);    //延时
   if(rxdone)
   { 
      return 0;
   }
   return 1;
}



//********************************************************
// 射频接收处理
//********************************************************
void radio_rx_handler()
{
  uint8_t     BufferSize=0;
  uint16_t    crc;

  Radio.GetPayload( rxbuffer, &BufferSize, BUFFER_SIZE );

  //-- 串口发送
  uart_tx_buffer[0] = 0x55;                                  //帧头
  uart_tx_buffer[1] = 0xAA;
  uart_tx_buffer[2] = 0x00;                                  //长度
  
  memcpy(uart_tx_buffer+3,rxbuffer+1,rxbuffer[1]+1);                
  crc=gen_crc(uart_tx_buffer+4,uart_tx_buffer[3]);           //crc
  uart_tx_buffer[uart_tx_buffer[3]+4] = crc>>8;
  uart_tx_buffer[uart_tx_buffer[3]+5] = crc&0xFF;
  uart_tx_buffer[uart_tx_buffer[3]+6] = 0xDD;                //帧尾

  UART_Send(UART0,uart_tx_buffer,uart_tx_buffer[3]+7);
}
//********************************************************
// CRC
//********************************************************
uint16_t crc_table[256] =
{
	0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7,
	0x8108, 0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF,
	0x1231, 0x0210, 0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6,
	0x9339, 0x8318, 0xB37B, 0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE,
	0x2462, 0x3443, 0x0420, 0x1401, 0x64E6, 0x74C7, 0x44A4, 0x5485,
	0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE, 0xF5CF, 0xC5AC, 0xD58D,
	0x3653, 0x2672, 0x1611, 0x0630, 0x76D7, 0x66F6, 0x5695, 0x46B4,
	0xB75B, 0xA77A, 0x9719, 0x8738, 0xF7DF, 0xE7FE, 0xD79D, 0xC7BC,
	0x48C4, 0x58E5, 0x6886, 0x78A7, 0x0840, 0x1861, 0x2802, 0x3823,
	0xC9CC, 0xD9ED, 0xE98E, 0xF9AF, 0x8948, 0x9969, 0xA90A, 0xB92B,
	0x5AF5, 0x4AD4, 0x7AB7, 0x6A96, 0x1A71, 0x0A50, 0x3A33, 0x2A12,
	0xDBFD, 0xCBDC, 0xFBBF, 0xEB9E, 0x9B79, 0x8B58, 0xBB3B, 0xAB1A,
	0x6CA6, 0x7C87, 0x4CE4, 0x5CC5, 0x2C22, 0x3C03, 0x0C60, 0x1C41,
	0xEDAE, 0xFD8F, 0xCDEC, 0xDDCD, 0xAD2A, 0xBD0B, 0x8D68, 0x9D49,
	0x7E97, 0x6EB6, 0x5ED5, 0x4EF4, 0x3E13, 0x2E32, 0x1E51, 0x0E70,
	0xFF9F, 0xEFBE, 0xDFDD, 0xCFFC, 0xBF1B, 0xAF3A, 0x9F59, 0x8F78,
	0x9188, 0x81A9, 0xB1CA, 0xA1EB, 0xD10C, 0xC12D, 0xF14E, 0xE16F,
	0x1080, 0x00A1, 0x30C2, 0x20E3, 0x5004, 0x4025, 0x7046, 0x6067,
	0x83B9, 0x9398, 0xA3FB, 0xB3DA, 0xC33D, 0xD31C, 0xE37F, 0xF35E,
	0x02B1, 0x1290, 0x22F3, 0x32D2, 0x4235, 0x5214, 0x6277, 0x7256,
	0xB5EA, 0xA5CB, 0x95A8, 0x8589, 0xF56E, 0xE54F, 0xD52C, 0xC50D,
	0x34E2, 0x24C3, 0x14A0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
	0xA7DB, 0xB7FA, 0x8799, 0x97B8, 0xE75F, 0xF77E, 0xC71D, 0xD73C,
	0x26D3, 0x36F2, 0x0691, 0x16B0, 0x6657, 0x7676, 0x4615, 0x5634,
	0xD94C, 0xC96D, 0xF90E, 0xE92F, 0x99C8, 0x89E9, 0xB98A, 0xA9AB,
	0x5844, 0x4865, 0x7806, 0x6827, 0x18C0, 0x08E1, 0x3882, 0x28A3,
	0xCB7D, 0xDB5C, 0xEB3F, 0xFB1E, 0x8BF9, 0x9BD8, 0xABBB, 0xBB9A,
	0x4A75, 0x5A54, 0x6A37, 0x7A16, 0x0AF1, 0x1AD0, 0x2AB3, 0x3A92,
	0xFD2E, 0xED0F, 0xDD6C, 0xCD4D, 0xBDAA, 0xAD8B, 0x9DE8, 0x8DC9,
	0x7C26, 0x6C07, 0x5C64, 0x4C45, 0x3CA2, 0x2C83, 0x1CE0, 0x0CC1,
	0xEF1F, 0xFF3E, 0xCF5D, 0xDF7C, 0xAF9B, 0xBFBA, 0x8FD9, 0x9FF8,
	0x6E17, 0x7E36, 0x4E55, 0x5E74, 0x2E93, 0x3EB2, 0x0ED1, 0x1EF0
};
uint16_t gen_crc(const uint8_t *buffer, int buffer_length)
{
	uint16_t crc = 0;
	int i;
	for (i = 0; i < buffer_length; i++)
		crc = crc_table[((crc >> 8) ^ buffer[i]) & 0xFF] ^ (crc << 8);
	return crc;
}
//********************************************************
// main
//********************************************************
int putchar(int ch)                                       //printf() 函数需要回调该函数
{
  uint8_t send = ch;
  UART_Send(UART0,&send,1); 
  return 0;
}

int main(void)
{
  uint16_t crc = 0;
  uint16_t crc1= 0;
  Lboard_init();          //板初始化
  sx1280_int();           //射频初始化
  UTIL_IdleUs(300000);    //延时
  Uart_init();

  for(;;)
  { 
     if(cmd_flag)       
     {
        cmd_flag=0;
        crc = gen_crc(uart_cmd_buffer+4,uart_cmd_buffer[3]);
        crc1=(uart_cmd_buffer[uart_cmd_buffer[3]+4]<<8)|(uart_cmd_buffer[uart_cmd_buffer[3]+5]);

        if( crc== crc1)
        {
           Uart_Parse();
           if(receive(6000)==0)
           {
              radio_rx_handler();
           }
           else
           {
              uart_tx_buffer[0] = 0x55;                                  //帧头
              uart_tx_buffer[1] = 0xAA;
              uart_tx_buffer[2] = 0x00;                                  //长度
              uart_tx_buffer[3] = 0x06;
              uart_tx_buffer[4] = 0x31;
              memcpy(uart_tx_buffer+4,uart_cmd_buffer+5,4);   
              uart_tx_buffer[9] = 0x00;          
              crc =  gen_crc(uart_tx_buffer+4,6);
              uart_tx_buffer[10] = crc>>8;       
              uart_tx_buffer[11] = crc;    
              uart_tx_buffer[12] = 0xDD;
              UART_Send(UART0,uart_tx_buffer,13);
           }
        }
        else
        {
           uart_tx_buffer[0] = 0x55;                                  //帧头
           uart_tx_buffer[1] = 0xAA;
           uart_tx_buffer[2] = 0x00;                                  //长度
           if(uart_cmd_buffer[4]==0x31)
           {
              uart_tx_buffer[3] = 0x06;
              uart_tx_buffer[4] = 0x31;
              memcpy(uart_tx_buffer+4,uart_cmd_buffer+5,4);   
              uart_tx_buffer[9] = 0x01;          
              crc =  gen_crc(uart_tx_buffer+4,6);
              uart_tx_buffer[10] = crc>>8;       
              uart_tx_buffer[11] = crc;    
              uart_tx_buffer[12] = 0xDD;
              UART_Send(UART0,uart_tx_buffer,13);        
           }
           else
           {
              uart_tx_buffer[3] = 0x02;
              uart_tx_buffer[4] = uart_cmd_buffer[4];
              uart_tx_buffer[5] = 0x01; 
              crc =  gen_crc(uart_tx_buffer+4,2);
              uart_tx_buffer[6] = crc>>8;       
              uart_tx_buffer[7] = crc; 
              uart_tx_buffer[8] = 0xDD; 
              UART_Send(UART0,uart_tx_buffer,9); 
           }
        }

        memset(uart_cmd_buffer,255,0);
     } 
  }
  return 0;
}
